//
//  ZGSTypeListViewController.m
//  MapleLeaf
//
//  Created by dllo on 15/11/27.
//  Copyright © 2015年 AntennaBabyTeam. All rights reserved.
//

#import "ZGSTypeListViewController.h"
#import "ZGSTypeListCell.h"
#import "ZGSSearchListViewController.h"
#import <MBProgressHUD.h>
#import <AFNetworking.h>
#import "BaseAFN.h"
#import "ZGSTypeModel.h"
#import "ZGSMoreCartoonViewController.h"
#import <UIImageView+WebCache.h>

#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
@interface ZGSTypeListViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UITextFieldDelegate>


@property(nonatomic, retain) UICollectionView *collecionView;
@property(nonatomic, retain) UICollectionViewFlowLayout *flowLayout;
@property(nonatomic, retain) UIView *headBgView;
@property(nonatomic, retain) UITextField *search;
@property(nonatomic, retain) NSMutableArray *typeArr;
@property(nonatomic, retain) NSMutableArray *hotArr;
@property(nonatomic, retain) MBProgressHUD *hud;

@end

@implementation ZGSTypeListViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}





#pragma mark - collectionDelegate & Datesource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.typeArr.count + 2;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ZGSTypeListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"tlReuse" forIndexPath:indexPath];
    if (indexPath.row < 3) {
        if (indexPath.row == 0) {
            cell.picView.image = [UIImage imageNamed:@"renqipaihang.png"];
            cell.titleLabel.text = @"人气排行";
        }
        else if (indexPath.row == 1) {
            cell.picView.image = [UIImage imageNamed:@"meirigengxin.png"];
            cell.titleLabel.text = @"每日排行";
        }
        else if (indexPath.row == 2) {
            cell.picView.image = [UIImage imageNamed:@"yonghengjingdian.png"];
            cell.titleLabel.text = @"永恒经典";
        }
    }
    else {
        [cell.picView sd_setImageWithURL:[NSURL URLWithString:[self.typeArr[indexPath.row - 3] pic]] placeholderImage:[UIImage imageNamed:@"back166.png"]];
        cell.titleLabel.text = [self.typeArr[indexPath.row - 3] name];
    }
    
    return cell;
}

#pragma mark - touchBegan

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesCancelled:touches withEvent:event];
    [self.view endEditing:YES];
}



- (void)createData {
    AFNetworkReachabilityManager *netManager = [AFNetworkReachabilityManager sharedManager];
    [netManager startMonitoring];
    [netManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == 1 || status == 2) {
            [BaseAFN GETURLByString:@"http://api.youqudao.com/mhapi/api/category/all/v2" AFNData:^(id result) {
                NSMutableArray *arr = result[@"data"][@"category"];
                self.typeArr = [NSMutableArray array];
                self.hotArr = [NSMutableArray array];
                self.typeArr = [ZGSTypeModel baseModelByArr:arr];
                self.hotArr = result[@"data"][@"keywords"];
                
                self.collecionView.hidden = NO;
                
                [self createHeadView];
                [self creatHotButton];
                [self.hud removeFromSuperview];
                [self.collecionView reloadData];
            }];

           
        }
        else {
            [self createHeadView];
            [self.hud removeFromSuperview];
            
            MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
            [self.view addSubview:hud];
            hud.mode = MBProgressHUDModeText;
            hud.labelText = @"数据请求失败,请检查网络后重试";
            [hud showAnimated:YES whileExecutingBlock:^{
                sleep(1);
            } completionBlock:^{
                [hud removeFromSuperview];
            }];
        }
    }];
    
    
}


- (void)createHeadView {
    self.headBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 64)];
    self.headBgView.backgroundColor = [UIColor colorWithRed:0.961f green:0.325f blue:0.173f alpha:1.00f];
    [self.view addSubview:self.headBgView];
  
    
    // 搜索栏
    self.search = [[UITextField alloc] initWithFrame:CGRectMake(50, 28, WIDTH - 120, 28)];
    self.search.backgroundColor = [UIColor whiteColor];
    self.search.layer.cornerRadius = 5;
    self.search.layer.masksToBounds = YES;
//    self.search.delegate = self;
    self.search.returnKeyType = UIReturnKeySearch;
    [self.search addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventEditingDidEndOnExit];
    [self.headBgView addSubview:self.search];

    
    // 返回键
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [backButton setBackgroundImage:[UIImage imageNamed:@"iconfont-fanhui2.png"] forState:UIControlStateNormal];
    backButton.frame = CGRectMake(10, 31, 20, 23);
    [backButton addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.headBgView addSubview:backButton];
    
    // 搜索键
    UIButton *searchButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [searchButton setTitle:@"搜索" forState:UIControlStateNormal];
    searchButton.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:16];
    searchButton.tintColor = [UIColor whiteColor];
    searchButton.frame = CGRectMake(WIDTH - 55, 28, 40, 28);
    [searchButton addTarget:self action:@selector(searchBAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.headBgView addSubview:searchButton];
    
    UIImageView *headImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -300, WIDTH, 200)];
    headImageView.image = [UIImage imageNamed:@"123.jpg"];
    [self.collecionView addSubview:headImageView];
    
    
    
    

}

- (UICollectionView *)collecionView {
    if (!_collecionView) {
        self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
        self.flowLayout.itemSize = CGSizeMake((WIDTH - 40) / 3, HEIGHT / 5);
        //        self.flowLayout.headerReferenceSize = CGSizeMake(WIDTH, 434);
        self.flowLayout.minimumInteritemSpacing = 10;
        self.flowLayout.minimumLineSpacing = 10;
        //        self.flowLayout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
        
        self.collecionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 44, WIDTH, HEIGHT - 44) collectionViewLayout:self.flowLayout];
        self.collecionView.contentInset = UIEdgeInsetsMake(300, 0, 0, 0);
        self.collecionView.backgroundColor = [UIColor whiteColor];
        self.collecionView.showsVerticalScrollIndicator = NO;
        self.collecionView.bounces = NO;
        [self.view addSubview:self.collecionView];
        
        self.collecionView.delegate = self;
        self.collecionView.dataSource = self;
    }
    return _collecionView;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    ZGSMoreCartoonViewController *clVC = [[ZGSMoreCartoonViewController alloc] init];
    if (indexPath.row == 0) {
        clVC.keyWord = @"热门";
    }
    else if (indexPath.row == 1){
        clVC.keyWord = @"最新";
    }
    else if (indexPath.row == 2) {
        clVC.keyWord = @"完结";
    }
    else {
        clVC.keyWord = [self.typeArr[indexPath.row - 3] name];
    }
    [self.navigationController pushViewController:clVC animated:YES];
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          }


- (void)creatHotButton {
    
    // 创建热门搜索键
    UILabel *hotLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, -95, 80, 20)];
    hotLabel.text = @"热门搜索:";
    hotLabel.font = [UIFont systemFontOfSize:16];
    hotLabel.textColor = [UIColor colorWithRed:37.000/255.000 green:125.000/255.000 blue:255.000/255.000 alpha:1];
    [self.collecionView addSubview:hotLabel];

    
    CGFloat x;
    CGFloat y = 10 * WIDTH / 375.0;
    CGFloat z = 220;
    NSString *regex = @"^[a-zA-Z]+$";
    NSPredicate *cate = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",regex];
    
    //button布局
    for (NSInteger i = 0; i < self.hotArr.count; i++) {
        
        if ([cate evaluateWithObject:self.hotArr[i]]) {
            x = [self.hotArr[i] length] * 10 * WIDTH / 375.0;
        }else{
            x = [self.hotArr[i] length] * 18 * WIDTH / 375.0;
        }
        
        if (y + x > self.view.frame.size.width) {
            z += 32;
            y = 10 * WIDTH / 375.0;
        }
        UIButton * hot = [UIButton buttonWithType:UIButtonTypeSystem];
        [hot setTitle:self.hotArr[i] forState:UIControlStateNormal];
        hot.titleLabel.font = [UIFont systemFontOfSize:15];
        hot.layer.borderWidth = 1;
        hot.layer.borderColor = [[UIColor colorWithRed:0.300f green:0.400f blue:0.700f alpha:0.250f] CGColor];
        hot.layer.cornerRadius = 3;
        hot.frame = CGRectMake(y, z - 290, x, 26);
        hot.tag = 1000 + i ;
        y += (x + 5 * WIDTH / 375.0);
        [hot addTarget:self action:@selector(hotSearchAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.collecionView addSubview:hot];
        
        
        
    }
}


//热门搜索用到的方法


- (void)hotSearchAction:(UIButton *)button {
    ZGSSearchListViewController *scVC = [[ZGSSearchListViewController alloc] init];
    scVC.keyWord = self.hotArr[button.tag - 1000];
    [self.navigationController pushViewController:scVC animated:YES];
    
}

- (void)searchAction:(UITextField *)textField {
    
    NSString *searchStr = textField.text;
    while ([searchStr hasPrefix:@" "]) {
        searchStr = [searchStr substringFromIndex:1];
    }
    
    if ([searchStr isEqualToString:@""]) {
        MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:hud];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"搜索框为空";
        hud.margin = 10 * HEIGHT / 667.0;
        
        [hud showAnimated:YES whileExecutingBlock:^{
            sleep(1.5);
        } completionBlock:^{
            [hud removeFromSuperview];
        }];
    }
    else {
        ZGSSearchListViewController *scVC = [[ZGSSearchListViewController alloc] init];
        scVC.keyWord = searchStr;
        [self.navigationController pushViewController:scVC animated:YES];
    }
    
}



- (void)searchBAction:(UIButton *)button {
    
    NSString *searchStr = self.search.text;
    while ([searchStr hasPrefix:@" "]) {
        searchStr = [searchStr substringFromIndex:1];
    }
    
    if ([searchStr isEqualToString:@""]) {
        MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:hud];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"搜索框为空";
        hud.margin = 10 * HEIGHT / 667.0;
        [hud showAnimated:YES whileExecutingBlock:^{
            sleep(1.5);
        } completionBlock:^{
            [hud removeFromSuperview];
        }];
    }
    else {
        ZGSSearchListViewController *scVC = [[ZGSSearchListViewController alloc] init];
        scVC.keyWord = searchStr;
        [self.navigationController pushViewController:scVC animated:YES];
    }
}
- (void)backAction:(UITextField *)textField {
    [self.navigationController popToRootViewControllerAnimated:YES];

}


- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.collecionView.hidden = YES;
    
    [self.collecionView registerClass:[ZGSTypeListCell class] forCellWithReuseIdentifier:@"tlReuse"];
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self createData];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
